package com.xtgg.history;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.loopj.android.http.RequestParams;
import com.umeng.analytics.MobclickAgent;
import com.xtgg.R;
import com.xtgg.manager.BaseActivity;
import com.xtgg.model.Resp;
import com.xtgg.sys.Constants;
import com.xtgg.sys.DemoApp;
import com.xtgg.util.MgqDataHandler;
import com.xtgg.util.MgqRestClient;
import com.xtgg.util.PreferencesUtils;
import com.xtgg.util.TLog;
import com.xtgg.util.ToastUtil;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.TextView;

public class HistoryMapActivity extends BaseActivity implements OnClickListener {
	MapView mMapView = null;
	BaiduMap mBaiduMap;
	JSONArray mArray;
	int mSelected;
	
	Marker mMarker;
	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_history_map);

		((TextView) findViewById(R.id.center)).setText("足迹");
		MobclickAgent.onEvent(this, ((TextView) findViewById(R.id.center))
				.getText().toString());

		((Button) findViewById(R.id.right)).setText("分享");
		((Button) findViewById(R.id.right)).setTextColor(Color
				.parseColor("#EE7C1C"));
		findViewById(R.id.left).setOnClickListener(this);
		findViewById(R.id.right).setOnClickListener(this);
		findViewById(R.id.layout0).setOnClickListener(this);
		findViewById(R.id.layout1).setOnClickListener(this);

		mMapView = (MapView) findViewById(R.id.bmapView);
		mBaiduMap = mMapView.getMap();
		mBaiduMap.setMyLocationEnabled(true);
		mBaiduMap.setOnMapStatusChangeListener(new OnMapStatusChangeListener()
		{
			@Override
			public void onMapStatusChange(MapStatus arg0) 
			{
				
			}

			@Override
			public void onMapStatusChangeFinish(MapStatus arg0) {
				
			}

			@Override
			public void onMapStatusChangeStart(MapStatus arg0) {
				findViewById(R.id.layout0).setVisibility(View.INVISIBLE);
				findViewById(R.id.layout1).setVisibility(View.INVISIBLE);
				
//				((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).
//					hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			}
		});
		
		MyLocationData locData = new MyLocationData.Builder()
		.accuracy(1000).direction(100)
		.latitude(((DemoApp)this.getApplicationContext()).mLat)
		.longitude(((DemoApp)this.getApplicationContext()).mLng).build();
		mBaiduMap.setMyLocationData(locData);
		
		LatLng ll = new LatLng(((DemoApp)this.getApplicationContext()).mLat,
				((DemoApp)this.getApplicationContext()).mLng);
		MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(ll,16);
		mBaiduMap.animateMapStatus(u);
		
		mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {
		    /** 
		    * 地图 Marker 覆盖物点击事件监听函数 
		    * @param marker 被点击的 marker 
		    */  
		    public boolean onMarkerClick(Marker marker)
		    {
		    	if(mMarker != null) mMarker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.ic_loc));
		    	mMarker = marker;
		    	
		    	BitmapDescriptor bitmap = BitmapDescriptorFactory  
					    .fromResource(R.drawable.ic_loc_s);  
		    	marker.setIcon(bitmap);
		    	mSelected = marker.getZIndex();
		    	
		    	JSONObject item = mArray.getJSONObject(mSelected);
		    	if(item.getString("alias").length() > 0) ((TextView)findViewById(R.id.addr)).setText(item.getString("alias"));
		    	else ((TextView)findViewById(R.id.addr)).setText(item.getString("place"));
		    	((TextView)findViewById(R.id.number)).setText(item.getString("number") + "个足迹");
		    	findViewById(R.id.layout0).setVisibility(View.VISIBLE);
		    	findViewById(R.id.layout1).setVisibility(View.GONE);
				return false;
		    }
		});
		
		final Date date = new Date(System.currentTimeMillis());
		((Button)findViewById(R.id.year)).setText(String.valueOf(1900 + date.getYear()));
		
		findViewById(R.id.year).setOnClickListener(this);
		findViewById(R.id.month0).setOnClickListener(this);
		findViewById(R.id.month1).setOnClickListener(this);
		findViewById(R.id.month2).setOnClickListener(this);
		findViewById(R.id.month3).setOnClickListener(this);
		findViewById(R.id.month4).setOnClickListener(this);
		findViewById(R.id.month5).setOnClickListener(this);
		findViewById(R.id.month6).setOnClickListener(this);
		findViewById(R.id.month7).setOnClickListener(this);
		findViewById(R.id.month8).setOnClickListener(this);
		findViewById(R.id.month9).setOnClickListener(this);
		findViewById(R.id.month10).setOnClickListener(this);
		findViewById(R.id.month11).setOnClickListener(this);

		findViewById(R.id.del).setOnClickListener(this);
		findViewById(R.id.modify).setOnClickListener(this);
		findViewById(R.id.confirm).setOnClickListener(this);

		findViewById(R.id.btn0).setOnClickListener(this);
		findViewById(R.id.btn1).setOnClickListener(this);
		findViewById(R.id.btn2).setOnClickListener(this);
		
		((Button)findViewById(R.id.month0 + date.getMonth())).setSelected(true);
		sendHttpRequest();
		
		final Handler handler = new Handler(){
			public void handleMessage(Message msg)
			{
				int xPos = (int) findViewById(R.id.month0 + date.getMonth()).getX();
				HorizontalScrollView hs = (HorizontalScrollView)findViewById(R.id.hs);
				hs.smoothScrollTo(xPos, 0);
				
				super.handleMessage(msg);
			}
		};
		
		new Timer().schedule(new TimerTask(){
			@Override
			public void run() {
				handler.sendEmptyMessage(0);
			}
		}, 200);
	}
	
	boolean hasDraw;
	Dialog mDialog = null;
	void showQuery() {
		mDialog = new Dialog(this, R.style.Dialog_Fullscreen);
		mDialog.setContentView(R.layout.dialog_share);
		mDialog.findViewById(R.id.action0).setOnClickListener(this);
		mDialog.findViewById(R.id.action1).setOnClickListener(this);
		mDialog.findViewById(R.id.action2).setOnClickListener(this);
		mDialog.findViewById(R.id.action3).setOnClickListener(this);
		mDialog.findViewById(R.id.login).setOnClickListener(this);
		mDialog.show();
	}
	
	 public Bitmap convertViewToBitmap(View view) {
		 WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		 int width = wm.getDefaultDisplay().getWidth();
		 int height = wm.getDefaultDisplay().getHeight();
		 
		 Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);  
		 view.draw(new Canvas(b));
		 return b;
	 }

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.right:
//			((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).
//			hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//			startActivity(new Intent(this,HistorySumActivity.class));
			showQuery();
			break;
			
		case R.id.left:
			finish();
			break;

		case R.id.btn2:
			startActivity(new Intent(this,SortActivity.class));
			finish();
			break;

		case R.id.btn0:
			finish();
			break;
			
		case R.id.year:
//			((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).
//				hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			showSex();
			break;

		case R.id.del:
			sendDelHttpRequest();
			break;
			
		case R.id.modify:
		{
			JSONObject item = mArray.getJSONObject(mSelected);
	    	if(item.getString("alias").length() > 0) ((TextView)findViewById(R.id.content)).setText(item.getString("alias"));
	    	else ((TextView)findViewById(R.id.content)).setText(item.getString("place"));
		}
			findViewById(R.id.layout0).setVisibility(View.GONE);
			findViewById(R.id.layout1).setVisibility(View.VISIBLE);
			break;
			
		case R.id.confirm:
			sendModifyHttpRequest();
			findViewById(R.id.layout0).setVisibility(View.GONE);
			findViewById(R.id.layout1).setVisibility(View.GONE);
			break;
		
		case R.id.month0:
		case R.id.month1:
		case R.id.month2:
		case R.id.month3:
		case R.id.month4:
		case R.id.month5:
		case R.id.month6:
		case R.id.month7:
		case R.id.month8:
		case R.id.month9:
		case R.id.month10:
		case R.id.month11:
//			((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).
//				hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			findViewById(R.id.layout0).setVisibility(View.INVISIBLE);
			findViewById(R.id.layout1).setVisibility(View.INVISIBLE);
			
			Button button = (Button)arg0;
			if(button.isSelected()) button.setSelected(false);
			else button.setSelected(true);
			sendHttpRequest();
			break;
		
		case R.id.action0:
		{
			HistorySumActivity.mScreenShot = convertViewToBitmap(findViewById(R.id.screen));
			
			Intent intent = new Intent(this,ShareActivity.class);
			intent.putExtra("type", 0);
			intent.putExtra("content", "小兔乖乖足迹");
			startActivity(intent);
		}
			mDialog.dismiss();
			break;
	
		case R.id.action1:
		{
			HistorySumActivity.mScreenShot = convertViewToBitmap(findViewById(R.id.screen));
			
			Intent intent = new Intent(this,ShareActivity.class);
			intent.putExtra("type", 1);
			intent.putExtra("content", "小兔乖乖足迹");
			startActivity(intent);
		}
			mDialog.dismiss();
			break;
	
		case R.id.action2:
		{
			HistorySumActivity.mScreenShot = convertViewToBitmap(findViewById(R.id.screen));
			
			Intent intent = new Intent(this,ShareActivity.class);
			intent.putExtra("type", 2);
			intent.putExtra("content", "小兔乖乖足迹");
			startActivity(intent);
		}
			mDialog.dismiss();
			break;
	
		case R.id.action3:
		{
			HistorySumActivity.mScreenShot = convertViewToBitmap(findViewById(R.id.screen));
			
			Intent intent = new Intent(this,ShareActivity.class);
			intent.putExtra("type", 3);
			intent.putExtra("content", "小兔乖乖足迹");
			startActivity(intent);
		}
			mDialog.dismiss();
			break;
		}
	}
	
	public void showSex() {
		Date date = new Date(System.currentTimeMillis());
		int year = 1900 + date.getYear();
		
		final String[] items = new String[20];
		for(int i = year; i > year - 20; i--)
		{
			items[year - i] = String.valueOf(i);
		}
		
		new AlertDialog.Builder(this).setTitle("选择年份")
		.setItems(items, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				((Button)findViewById(R.id.year)).setText(items[which]);
				sendHttpRequest();
			}
		}).show();
	}
	
	private void sendHttpRequest() {
		mBaiduMap.clear();
		
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				TLog.d(TAG, "response=" + response);
				Resp ruser = JSON.parseObject(response, Resp.class);
				if (ruser.getState().equals("1")) {
					
					mArray = JSON.parseObject(response).getJSONArray("data");
					final Handler handle = new Handler()
					{
						public void handleMessage(Message msg)
						{
							JSONObject item = mArray.getJSONObject(msg.what);
							if(item.getString("latitude").length() == 0 || item.getString("latitude").length() == 0) return;
							
							LatLng point = new LatLng(item.getDoubleValue("latitude"),item.getDoubleValue("longitude"));  
							BitmapDescriptor bitmap = BitmapDescriptorFactory  
							    .fromResource(R.drawable.ic_loc);  
							//构建MarkerOption，用于在地图上添加Marker  
							OverlayOptions option = new MarkerOptions()  
							    .position(point)  
							    .icon(bitmap).zIndex(msg.what);  
							mBaiduMap.addOverlay(option);
						}
					};
					
					new Thread()
					{
						public void run()
						{
							int count = mArray.size();
							for(int i = 0; i < count; i++)
							{
								handle.sendEmptyMessage(i);
								try 
								{
									Thread.sleep(10);
								} 
								catch (InterruptedException e) {
									e.printStackTrace();
								}
							}
						}
					}.start();
				}
				else if (ruser.getState().equals("2"))
				{
					showExitDialog();
				} 
				else {
					ToastUtil.showToastWithAlertPic(ruser.getMessage());
				}
			}
		};
		// -----------------------
		
		StringBuffer buffer = new StringBuffer();
		for(int i = 0; i < 12; i++)
		{
			if(((Button)findViewById(R.id.month0 + i)).isSelected())
			{
				buffer.append(String.valueOf(i + 1));
				buffer.append(",");
			}
		}
		
		if(buffer.length() > 0)buffer.deleteCharAt(buffer.length() - 1);
		
		RequestParams params = new RequestParams();
		params.put("act", "myFootMark");
		params.put("userid", PreferencesUtils.getString(this, "userid"));
		params.put("year",((Button)findViewById(R.id.year)).getText().toString());
		params.put("month",buffer.toString());
		MgqRestClient.get(Constants.INFOMGT, params, loginHandler);
	}
	
	private void sendDelHttpRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				TLog.d(TAG, "response=" + response);
				Resp ruser = JSON.parseObject(response, Resp.class);
				if (ruser.getState().equals("1")) {
					ToastUtil.showToastWithAlertPic("足迹删除成功");
					sendHttpRequest();

					findViewById(R.id.layout0).setVisibility(View.GONE);
					findViewById(R.id.layout1).setVisibility(View.GONE);
				} 
				else if (ruser.getState().equals("2"))
				{
					showExitDialog();
				} 
				else {
					ToastUtil.showToastWithAlertPic(ruser.getMessage());
				}
			}
		};
		// -----------------------
		RequestParams params = new RequestParams();
		params.put("act", "delFootMark");
		params.put("footmarkid", mArray.getJSONObject(mSelected).getString("footmarkid"));
		MgqRestClient.get(Constants.INFOMGT, params, loginHandler);
	}
	
	private void sendModifyHttpRequest() {
		String content = ((EditText)findViewById(R.id.content)).getText().toString();
		if(content.length() == 0) 
		{
			ToastUtil.showToastWithAlertPic("请输入修改内容");
			return;
		}
		
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				TLog.d(TAG, "response=" + response);
				Resp ruser = JSON.parseObject(response, Resp.class);
				if (ruser.getState().equals("1")) {
					ToastUtil.showToastWithAlertPic("足迹修改成功");
					sendHttpRequest();

					findViewById(R.id.layout0).setVisibility(View.GONE);
					findViewById(R.id.layout1).setVisibility(View.GONE);
				}
				else if (ruser.getState().equals("2"))
				{
					showExitDialog();
				} 
				else {
					ToastUtil.showToastWithAlertPic(ruser.getMessage());
				}
			}
		};

		JSONObject item = mArray.getJSONObject(mSelected);
		
		RequestParams params = new RequestParams();
		params.put("act", "updateFootMark");
		params.put("userid", PreferencesUtils.getString(this, "userid"));
		params.put("province", item.getString("province"));
		params.put("city", item.getString("city"));
		params.put("place", item.getString("place"));
		params.put("alias", content);
		MgqRestClient.get(Constants.INFOMGT, params, loginHandler);
	}
}
